/*
 * 版权所有 (c) 2022-2099 TBIT。保留所有权利。
 */

package com.tbit.main.util;

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.Header;
import cn.hutool.http.useragent.UserAgent;
import cn.hutool.http.useragent.UserAgentParser;
import com.tbit.common.constant.SystemConstant;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * @author <a href="mailto:li.yao@tbit.com.cn">yao</a>
 * @version 4.1.0
 * @since 2024/8/5 11:54
 */
public final class OrderSourceUtils {

    public static Integer getOrderSource() {
        // 默认安卓
        int orderSource = 4;

        RequestAttributes requestAttributes = RequestContextHolder.currentRequestAttributes();

        if (requestAttributes instanceof ServletRequestAttributes) {

            //获取Request
            HttpServletRequest request = ((ServletRequestAttributes) requestAttributes).getRequest();

            String orderSourceHeader = request.getHeader(SystemConstant.ORDER_SOURCE);
            if (StrUtil.isNotBlank(orderSourceHeader)) {
                return Integer.parseInt(orderSourceHeader);
            }

            String userAgentStr = request.getHeader(Header.USER_AGENT.getValue());
            if (StrUtil.isNotBlank(userAgentStr)) {
                UserAgent userAgent = UserAgentParser.parse(userAgentStr);
                if (userAgent.getPlatform().isIos()) {
                    // IOS
                    orderSource = 5;
                }
            }
        }

        return orderSource;
    }

}
